package com.igeek.health.config;

import cn.hutool.core.collection.CollectionUtil;
import com.igeek.health.entity.Permission;
import com.igeek.health.entity.Role;
import com.igeek.health.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/14  9:31
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
    private User user;

    public LoginUser(User user) {
        this.user = user;
    }

    private List<GrantedAuthority> authorityList;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(CollectionUtil.isNotEmpty(authorityList)){
            return authorityList;
        }
        authorityList = new ArrayList<GrantedAuthority>();
        Set<Role> roles = user.getRoles();
        roles.forEach(role -> {
            authorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            permissions.forEach(permission -> authorityList.add(new SimpleGrantedAuthority(permission.getKeyword())));
        });
        return authorityList;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStation().equals("1");
    }
}
